package com.dxq.test.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dxq.test.App;
import com.dxq.test.common.AppManager;
import com.dxq.test.R;
import com.dxq.test.db.Breed;
import com.dxq.test.db.Label;
import com.dxq.test.db.LabelBreed;
import com.dxq.test.db.Pasture;
import com.dxq.test.db.TablesDao;
import com.dxq.test.utils.DialogClickListener;
import com.dxq.test.utils.MyUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import java.util.Date;
import java.util.List;

/**
 * Author: zsh
 * Date: 2023/11/18
 * Describe: 配种添加、修改、删除页面
 */
public class BreedAddActivity extends AppCompatActivity implements View.OnClickListener, OnDateSetListener {

    public TablesDao tablesDao;

    private ImageView ivBack;
    private TextView tvTitle, tvSet;
    private Button btnSubmit;
    private LinearLayout llCode;
    private TextView tvCode, tvWLabel, tvMLabel, tvTime, tvBirthTime, tvNextTime;
    private ImageView ivSelectW, ivSelectM;
    private EditText etRemark;
    private CheckBox cbBirthTimeRemind, cbNextTimeRemind;

    private Typeface font;

    private Breed breed;
    private Label labelMSelect, labelWSelect;

    private int selectTime = 0;
    private TimePickerDialog mDialogAllTime;//选择时间控件

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //添加Activity到堆栈
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_breed_add);
        breed = (Breed) getIntent().getSerializableExtra("breed");
        //label = (Label) getIntent().getSerializableExtra("label");
        tablesDao = new TablesDao(this);
        font = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        initView();
        initTimePicker();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在appManager结束当前activity
        AppManager.getAppManager().finishActivity(this);
    }

    private void initView() {
        ivBack = findViewById(R.id.ivBack);
        tvTitle = findViewById(R.id.tvTitle);
        tvSet = findViewById(R.id.tvSet);
        tvTitle.setText("配种记录");
        tvSet.setText("删除");

        llCode = findViewById(R.id.llCode);
        tvCode = findViewById(R.id.tvCode);
        tvWLabel = findViewById(R.id.tvWLabel);
        tvMLabel = findViewById(R.id.tvMLabel);
        tvTime = findViewById(R.id.tvTime);
        tvBirthTime = findViewById(R.id.tvBirthTime);
        tvNextTime = findViewById(R.id.tvNextTime);
        ivSelectW = findViewById(R.id.ivSelectW);
        ivSelectM = findViewById(R.id.ivSelectM);
        cbBirthTimeRemind = findViewById(R.id.cbBirthTimeRemind);
        cbNextTimeRemind = findViewById(R.id.cbNextTimeRemind);
        etRemark = findViewById(R.id.etRemark);
        btnSubmit = findViewById(R.id.btnSubmit);

        if (null == breed) {
            tvSet.setVisibility(View.GONE);
            llCode.setVisibility(View.GONE);
        } else {
            tvSet.setVisibility(View.VISIBLE);
            llCode.setVisibility(View.VISIBLE);
            tvCode.setText(breed.getCode());
            labelWSelect = breed.getLabel_w();//赋值
            if (labelWSelect != null)
                tvWLabel.setText(labelWSelect.getName());
            labelMSelect = breed.getLabel_m();//赋值
            if (labelMSelect != null)
                tvMLabel.setText(labelMSelect.getName());
            tvTime.setText(breed.getTime());
            tvBirthTime.setText(breed.getBirth_time());
            tvNextTime.setText(breed.getNext_time());
            cbBirthTimeRemind.setChecked(breed.isBirth_time_remind());
            cbNextTimeRemind.setChecked(breed.isNext_time_remind());
            etRemark.setText(breed.getRemark());
        }

        ivBack.setOnClickListener(this);
        tvSet.setOnClickListener(this);
        ivSelectW.setOnClickListener(this);
        ivSelectM.setOnClickListener(this);
        tvTime.setOnClickListener(this);
        tvBirthTime.setOnClickListener(this);
        tvNextTime.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
    }

    private void initTimePicker() {
        //初始化时间控件
        long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
        mDialogAllTime = new TimePickerDialog.Builder()
                .setCallBack(BreedAddActivity.this)
                .setCancelStringId("取消")
                .setSureStringId("确定")
                .setTitleStringId("选择时间")
                .setYearText("年")
                .setMonthText("月")
                .setDayText("日")
                .setHourText("时")
                .setMinuteText("分")
//                .setCyclic(false)
//                .setMinMillseconds(System.currentTimeMillis())
//                .setMaxMillseconds(System.currentTimeMillis() + 3 * tenYears)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                .setType(Type.ALL)
                .setWheelItemTextNormalColor(getResources().getColor(R.color.timetimepicker_default_text_color))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.blu))
                .setWheelItemTextSize(12)
                .build();
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        switch (selectTime) {
            case 0:
                tvTime.setText(TimeUtils.millis2String(millseconds));
                break;

            case 1:
                tvBirthTime.setText(TimeUtils.millis2String(millseconds));
                break;

            case 2:
                tvNextTime.setText(TimeUtils.millis2String(millseconds));
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                this.finish();
                break;

            case R.id.tvSet://删除
                MyUtil.normalDialog(BreedAddActivity.this, "操作提示", "是否删除配种信息？",
                        "取消", "确定", new DialogClickListener() {

                            @Override
                            public void onNegativeClick() {

                            }

                            @Override
                            public void onPositiveClick() {
                                deleteVaccine();
                            }
                        });
                break;

            case R.id.ivSelectM://选择配种对应的牲畜（公）
                Intent intent1 = new Intent(BreedAddActivity.this, StockSelectActivity.class);
                intent1.putExtra("selectSex", 1);
                startActivityForResult(intent1, 101);
                break;

            case R.id.ivSelectW://选择配种对应的牲畜（母）
                Intent intent2 = new Intent(BreedAddActivity.this, StockSelectActivity.class);
                intent2.putExtra("selectSex", 2);
                startActivityForResult(intent2, 102);
                break;

            case R.id.tvTime://选择配种时间
                selectTime = 0;
                mDialogAllTime.show(getSupportFragmentManager(), "all");
                break;

            case R.id.tvBirthTime://选择预产日期
                selectTime = 1;
                mDialogAllTime.show(getSupportFragmentManager(), "all");
                break;

            case R.id.tvNextTime://选择二次配种时间
                selectTime = 2;
                mDialogAllTime.show(getSupportFragmentManager(), "all");
                break;

            case R.id.btnSubmit://提交
                submit();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            if (requestCode == 101) {
                //选公
                labelMSelect = (Label) data.getSerializableExtra("label");
                tvMLabel.setText(labelMSelect.getName());
                return;
            }
            if (requestCode == 102) {
                //选母
                labelWSelect = (Label) data.getSerializableExtra("label");
                tvWLabel.setText(labelWSelect.getName());
                return;
            }
        }
    }

    //删除vaccine
    private void deleteVaccine() {
        int result = tablesDao.deleteBreed(breed);
        if (result != 1) {
            ToastUtils.showShort("删除失败, breed");
            return;
        }
        //接着删除关联表
        List<LabelBreed> labelBreeds = tablesDao.queryLabelBreedByBreed(breed);
        int res = tablesDao.deleteLabelBreed(labelBreeds);
        ToastUtils.showShort("删除成功");
        this.finish();
    }

    private void submit() {
        String localMName = tvMLabel.getText().toString();
        String localWName = tvWLabel.getText().toString();
        String time = tvTime.getText().toString();
        String birthTime = tvBirthTime.getText().toString();
        String nextTime = tvNextTime.getText().toString();
        boolean isBirthTimeRemind = cbBirthTimeRemind.isChecked();
        boolean isNextTimeRemind = cbNextTimeRemind.isChecked();
        String remark = etRemark.getText().toString();
        if (localWName.equals("")) {
            ToastUtils.showShort("请选择母羊");
            return;
        }
        if (localMName.equals("")) {
            ToastUtils.showShort("请选择公羊");
            return;
        }
        if (time.equals("")) {
            ToastUtils.showShort("请选择配种日期");
            return;
        }
        if (isBirthTimeRemind) {
            if (birthTime.equals("")) {
                ToastUtils.showShort("请选择预产日期");
                return;
            }
        }
        if (isNextTimeRemind) {
            if (nextTime.equals("")) {
                ToastUtils.showShort("请选择下次防治日期");
                return;
            }
        }
        if (null == breed) {
            //查询当前所选择牧场
            Pasture pasture = tablesDao.queryPastureById(App.select_pasture_id);
            //新增
            String code = "PZ" + MyUtil.date2String(new Date());
            Breed breed = new Breed(code, time, birthTime, nextTime, isBirthTimeRemind, isNextTimeRemind, remark, pasture);
            //1、创建配种
            int result = tablesDao.insertBreed(breed);
            if (result == 1) {
                //2、创建牲畜配种关联数据
                LabelBreed labelBreed = new LabelBreed(labelMSelect, labelWSelect, breed);
                int res = tablesDao.insertLabelBreed(labelBreed);
                if (res == 1) {
                    //3、创建成功，返回页面
                    ToastUtils.showShort("新增成功");
                    this.finish();
                    return;
                } else {
                    //4、创建失败，删除创建成功的配种数据
                    ToastUtils.showShort("新增失败，配种关联数据");
                    tablesDao.deleteBreed(breed);
                }
            }
            ToastUtils.showShort("新增失败，配种");
        } else {
            //修改
            //如果修改了牲畜，需要更改牲畜信息
            if (labelWSelect != null && !labelWSelect.getName().equals(breed.getLabel_w().getName()) ||
                    labelMSelect != null && !labelMSelect.getName().equals(breed.getLabel_m().getName())) {
                //1、查询出旧的关联数据
                List<LabelBreed> labelBreeds = tablesDao.queryLabelBreedByBreed(breed);
                //2、新增新的关联数据
                LabelBreed labelBreed = new LabelBreed(labelMSelect, labelWSelect, breed);
                tablesDao.insertLabelBreed(labelBreed);
                //3、删除旧的关联数据
                if (!ObjectUtils.isEmpty(labelBreeds)) {
                    tablesDao.deleteLabelBreed(labelBreeds.get(0));
                }
            }
            Breed b = tablesDao.queryBreedById(breed.getBreed_id());
            b.setTime(time);
            b.setBirth_time(birthTime);
            b.setNext_time(nextTime);
            b.setBirth_time_remind(isBirthTimeRemind);
            b.setNext_time_remind(isNextTimeRemind);
            b.setRemark(remark);
            int result = tablesDao.updateBreed(b);
            if (result == 1) {
                ToastUtils.showShort("更新成功");
                this.finish();
                return;
            }
            ToastUtils.showShort("更新失败，配种");
        }
    }

    @Override
    public void onBackPressed() {
        this.finish();
    }
}
